<template>
  <div>
    <el-card class="member-box-card">
      <div class="block">
        <span class="demonstration">时间选择 </span>
        <el-date-picker
          v-model="value2"
          value-format="yyyy/MM/dd HH:mm:ss"
          @change="handleDate(value2)"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right">
        </el-date-picker >
        <el-button
          size="mini"
          type="primary"
          @click="refresh()"
          style="margin-left: 10px"
        >刷新</el-button>
      </div>
      <el-table id="member-table" :key="itemKey" v-loading="loading" :data="tableData"
                border style="width: 100%" >
        max-height="450"
        <el-table-column prop="id" label="序号" />
        <el-table-column prop="requisitionId" label="流水号"/>
        <el-table-column prop="name" label="货物名称" />
        <el-table-column prop="specification" label="型号" />
        <el-table-column prop="unit" label="规格" />
        <el-table-column prop="position"  label="存放位置" />
        <el-table-column prop="outDate"  label="出库时间" />
        <el-table-column prop="outNum" label="出库数量" />
        <el-table-column prop="purpose" label="用途" />
        <el-table-column prop="receiver" label="领用人" />
        <el-table-column prop="storeNum" label="库存数量" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column align="right">
          <template slot="header" slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="setExport2Excel()"
            >导出</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--<el-pagination
      background
      layout="prev, pager, next"
      :total="1000"
     style="width: 80px; margin-left: 350px">
    </el-pagination>-->
  </div>
</template>

<script>
  import {selectAllDelivery,selectBetweenDate,selectRequisitionId} from '@/api/material-delivery/delivery-form'
  import { getToken } from '@/utils/auth'
  import dateFormat from 'dateformat'

  export default {
    name: 'index',
    data() {
      return {
        tableData: [],
        state: '',
        itemKey: '',
        loading: false,
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        selectValue: '',
        requisitionId:'',
        value2: '',
        headers: {
          Authorization: getToken()
        }
      };
    },

    created() {
      this.init()
    },
    methods: {
      init() {
        selectAllDelivery().then((response) => {
          this.tableData = response.data
        })
      },
      handleDate(value2) {
        console.log(value2)
        //this.loading = true
        selectBetweenDate(value2[0], value2[1]).then((response) => {
          this.tableData = response.data
          this.loading = false
          this.itemKey = Math.random()
        })
      },

      refresh(){
        console.log(value2)
        selectAllDelivery().then((response) => {
          this.tableData = response.data
        })
      },
      querySearch(queryString, cb) {
        var searchDatas = this.tableData;
        var results = queryString ? searchDatas.filter(this.createStateFilter(queryString)) : searchDatas;
        var results1 = []
        for (let i = 0; i < results.length; i++) {
          results1.push({
            'value': results[i].requisitionId
          })
        }
        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          cb(results1);
        }, 2000 * Math.random());
      },

      createStateFilter(queryString)
      {
        return (state) => {
          return (state.requisitionId.toLowerCase().indexOf(queryString.toLowerCase()) > -1);
        };
      },
      handleSelect(item) {
        selectRequisitionId(item.value).then((response) => {
          this.selectValue = item.value
          this.tableData = response.data
          this.itemKey = Math.random()
        })
      },
      setExport2Excel()
      {
        require
          .ensure([], () => {
            const { export_json_to_excel} = require("@/excel/export2Excel");
            const title = [
              "检测中心材料消耗出库登记表","","","","","","","","","","",""
            ];
            const date = [
              "          年        月         日                                                                                                                      负责人：","","","","","","","","","","",""
            ]
            const tHeader = [
              "序号",
              //"流水号",
              "货物名称",
              "型号",
              "规格",
              "存放位置",
              "出库时间",
              "出库数量",
              "用途",
              "领用人",
              "库存数量",
              "备注"
            ]; // 上面设置Excel的表格第一行的标题
            const filterVal = [
              "id",
             // "requisitionId",
              "name",
              "specification",
              "unit",
              "position",
              "outDate",
              "outNum",
              "purpose",
              "receiver",
              "storeNum",
              "remark"
            ];

            const list = this.tableData; //把要导出的数据tableData存到list   这个数组不能为空

            const data = this.formatJson(filterVal, list);
            export_json_to_excel(title,date,tHeader, data, "出库登记表");
          })

          .catch((err) => {
            console.log(66666);
          });
      },
      //格式转换,不需要改动
      formatJson(filterVal, jsonData) {
        console.log(jsonData);
        return jsonData.map((v) => filterVal.map((j) => v[j]));
      }

   /*   setExport2Excel() {
        /* generate workbook object from table */
      /* var wb = XLSX2.utils.table_to_sheet(document.querySelector("#member-table"));//mytable为表格的id名
         if (!wb['!merges']) {//这个是当表格有合并的时候才会存在，并不是判断有无数据的标准
          this.$message.warning('无法导出：报表无数据');
          return
        }
        for (var i = 0; i < 11; i++) {
          wb["!cols"][i] = { wpx: 130 }
        }
        // 样式的文档地址
        // https://www.npmjs.com/package/xlsx-style
        for (const key in wb) {
          if (key.indexOf('!') === -1 && wb[key].v) {
            wb[key].s = {
              font: {//字体设置
                sz: 13,
                bold: false,
                color: {
                  rgb: '000000'//十六进制，不带#
                }
              },
              alignment: {//文字居中
                horizontal: 'center',
                vertical: 'center',
                wrap_text: true
              },
              border: { // 设置边框
                top: { style: 'thin' },
                bottom: { style: 'thin' },
                left: { style: 'thin' },
                right: { style: 'thin' }
              }
            }
          }
        }
        var data = this.addRangeBorder(wb['!merges'], wb) //合并项添加边框
        var filedata = this.sheet2blob(data)
        this.openDownloadDialog(filedata, this.todayTimeString + "出库登记表.xlsx")
      },
      //为合并项添加边框
      addRangeBorder(range, ws) {
        let arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];

        range.forEach(item => {
          let startColNumber = Number(item.s.r), endColNumber = Number(item.e.r);
          let startRowNumber = Number(item.s.c), endRowNumber = Number(item.e.c);
          const test = ws[arr[startRowNumber] + (startColNumber + 1)];
          for (let col = startColNumber; col <= endColNumber; col++) {
            for (let row = startRowNumber; row <= endRowNumber; row++) {
              ws[arr[row] + (col + 1)] = test;
            }
          }
        })
        return ws;
      },
      //将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
      sheet2blob(sheet, sheetName) {
        sheetName = sheetName || 'sheet1';
        var workbook = {
          SheetNames: [sheetName],
          Sheets: {}
        };
        workbook.Sheets[sheetName] = sheet; // 生成excel的配置项

        var wopts = {
          bookType: 'xlsx', // 要生成的文件类型
          bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
          type: 'binary'
        };
        var wbout = XLSX.write(workbook, wopts);
        var blob = new Blob([s2ab(wbout)], {
          type: "application/octet-stream"
        }); // 字符串转ArrayBuffer
        function s2ab(s) {
          var buf = new ArrayBuffer(s.length);
          var view = new Uint8Array(buf);
          for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
          return buf;
        }

        return blob;
      },
      openDownloadDialog(url, saveName) {
        if (typeof url == 'object' && url instanceof Blob) {
          url = URL.createObjectURL(url); // 创建blob地址
        }
        var aLink = document.createElement('a');
        aLink.href = url;
        aLink.download = saveName || '物料出库记录表'; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
        var event;
        if (window.MouseEvent) event = new MouseEvent('click');
        else {
          event = document.createEvent('MouseEvents');
          event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        }
        aLink.dispatchEvent(event);
      }
*/
    }

  }
</script>

<style scoped>
  .member-box-card {
    width: 95%;
    margin: 20px auto;
  }
  #member-table {
    margin-top: 5px;
  }

</style>
